package com.invoicerecognition.backend.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ListMapTypeHandler extends BaseTypeHandler<List<Map<String, String>>> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Map<String, String>> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (IOException e) {
            throw new SQLException("Error converting List<Map<String, String>> to JSON", e);
        }
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        try {
            return json == null ? new ArrayList<>() : objectMapper.readValue(json, new TypeReference<List<Map<String, String>>>() {});
        } catch (IOException e) {
            throw new SQLException("Error converting JSON to List<Map<String, String>>", e);
        }
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        try {
            return json == null ? new ArrayList<>() : objectMapper.readValue(json, new TypeReference<List<Map<String, String>>>() {});
        } catch (IOException e) {
            throw new SQLException("Error converting JSON to List<Map<String, String>>", e);
        }
    }

    @Override
    public List<Map<String, String>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        try {
            return json == null ? new ArrayList<>() : objectMapper.readValue(json, new TypeReference<List<Map<String, String>>>() {});
        } catch (IOException e) {
            throw new SQLException("Error converting JSON to List<Map<String, String>>", e);
        }
    }
}
